package com.idea.relax.exception.toolkit;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.UndeclaredThrowableException;

/**
 * @author: 沉香
 * @date: 2023/2/20
 * @description: 异常工具类
 */
public class Exceptions {

	/**
	 * 将CheckedException转换为UncheckedException.
	 *
	 * @param e Throwable
	 * @return RuntimeException
	 */
	public static RuntimeException unchecked(Throwable e) {
		if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
			|| e instanceof NoSuchMethodException) {
			return new IllegalArgumentException(e);
		} else if (e instanceof InvocationTargetException) {
			return new RuntimeException(((InvocationTargetException) e).getTargetException());
		} else if (e instanceof RuntimeException) {
			return (RuntimeException) e;
		} else {
			return new RuntimeException(e);
		}
	}

	/**
	 * 代理异常解包
	 *
	 * @param wrapped 包装过得异常
	 * @return 解包后的异常
	 */
	public static Throwable unwrap(Throwable wrapped) {
		Throwable unwrapped = wrapped;
		while (true) {
			if (unwrapped instanceof InvocationTargetException) {
				unwrapped = ((InvocationTargetException) unwrapped).getTargetException();
			} else if (unwrapped instanceof UndeclaredThrowableException) {
				unwrapped = ((UndeclaredThrowableException) unwrapped).getUndeclaredThrowable();
			} else {
				return unwrapped;
			}
		}
	}

	/**
	 * 获取指定包名为前缀的堆栈异常信息
	 *
	 * @param throwable 异常
	 * @param prefix    指定的包前缀
	 * @return 堆栈信息
	 */
	public static StackTraceElement getStackTraceByPrefix(Throwable throwable, String prefix) {
		return getStackTraceByPrefix(throwable, prefix, 3);
	}


	public static StackTraceElement getStackTraceByPrefix(Throwable throwable, String prefix, int searchMax) {
		int position = 0;
		StackTraceElement[] trace = throwable.getStackTrace();
		for (StackTraceElement e : trace) {
			if (e.getClassName().startsWith(prefix)) {
				return e;
			}
		}
		position++;
		if (position == searchMax) {
			return null;
		}
		int length = prefix.split("\\.").length;
		if (length == 1) {
			return null;
		}
		prefix = prefix.substring(0, prefix.lastIndexOf('.'));
		return getStackTraceByPrefix(throwable, prefix, searchMax);
	}

}
